package xh;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2016/7/6.
 */
public class DownloadManager {

    private FileListManager fileListManager;

    ScheduledExecutorService fileDownloadSchedule;

    Map<String, DownloadTask> taskList = new HashMap<String, DownloadTask>();


    public DownloadManager(FileListManager fileListManager) {
        this.fileListManager = fileListManager;
    }

    public void start() {

        fileDownloadSchedule = Executors.newScheduledThreadPool(1);
        fileDownloadSchedule.scheduleAtFixedRate(new ScanForDownload(), 5, 5, TimeUnit.SECONDS);

    }


    private class ScanForDownload implements Runnable {

        public void run() {

            List<FileListManager.FileInfo> fileInfos = fileListManager.allRemoteFiles();

            synchronized (taskList) {

                // remove finished
                Iterator itr = taskList.entrySet().iterator();
                for (; itr.hasNext(); ) {
                    Map.Entry<String, DownloadTask> next = (Map.Entry<String, DownloadTask>) itr.next();
                    DownloadTask d = next.getValue();
                    if (d.finished) {
                        itr.remove();
                    }
                }

                for (FileListManager.FileInfo f : fileInfos) {

                    if (taskList.containsKey(f.fileId)) {
                        continue;
                    }

                    DownloadTask downloadTask = new DownloadTask(f);

                    taskList.put(f.fileId, downloadTask);

                    new Thread(downloadTask).start();
                }
            }
        }
    }


    private class DownloadTask implements Runnable {
        private final FileListManager.FileInfo fileInfo;
        boolean finished = false;

        public DownloadTask(FileListManager.FileInfo fileInfo) {
            this.fileInfo = fileInfo;
        }

        public void run() {
            new DownLoadFile().download(fileInfo);

            // load file list

            fileListManager.reloadFileListNow();

            finished = true;
        }
    }
}
